<template>
  <div class="app-container">
    <el-row class="mb20">
      <el-tabs v-model="currentOrderType" @tab-click="handleOrderTypeClick">
        <el-tab-pane label="长短租" name="1"></el-tab-pane>
        <el-tab-pane label="日租" name="2"></el-tab-pane>
      </el-tabs>
    </el-row>
    <el-row class="mb20">
      <el-radio-group v-model="queryType" @change="handleQueryType">
        <el-radio-button label="card">卡片</el-radio-button>
        <el-radio-button label="list">列表</el-radio-button>
      </el-radio-group>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="日期" prop="nowTime" v-if="queryType === 'list'">
        <el-date-picker @change="startTimeChange" value-format="yyyy-MM-dd" v-model="queryParams.nowTime" type="date"
                        placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="楼盘" prop="estateId">
        <el-select v-model="queryParams.estateId" placeholder="" clearable filterable style="width: 240px">
          <el-option v-for="dict in estateList" :key="dict.estateId" :label="dict.estateName" :value="dict.estateId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="房间状态" prop="onlineRentalType" v-if="queryType === 'list'">
        <el-select v-model="queryParams['housingAllocation.apartmentState']" placeholder="" clearable
                   style="width: 240px"
        >
          <el-option label="已上架" value="0"/>
          <el-option label="已下架" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-`icon`-sea`rch" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="query-button">
      <el-button :type="current === index ? 'primary' : ''" v-for="(item, index) in queryButton" :key="index"
                 @click="handleQueryButton(item, index)"
      >{{
          item.label
        }}
      </el-button>
    </div>
    <right-toolbar
      :showSearch.sync="showSearch"
      @queryTable="getList"
    ></right-toolbar>
    <div class="order-state-tip">
      <div class="state-tip-item" v-for="item in orderStateTipList" :key="item.value">
        <div :class="'square ' +item.class "></div>
        <span>{{ item.label }}</span>
      </div>
    </div>

    <!--  列表  -->
    <el-table v-loading="loading" v-if="queryType === 'list'" :data="roomList" ref="table" border>
      <el-table-column label="房间" prop="premisesAddress" :show-overflow-tooltip="true" width="250" :resizable="true"
                       fixed
      >
        <template slot-scope="scope">
          <div>
            <svg-icon icon-class="zang" v-if="scope.row.sweepState === '1' || scope.row.sweepState === '2'"
                      style="margin-right: 10px; font-size: 18px;color: red;"
            />
            <span>{{ scope.row.premisesAddress }}</span></div>
        </template>
      </el-table-column>
      <el-table-column v-for="(date) in dateList" :key="date.date" :resizable="false" :label-class-name="compareDate(date.date, new Date())? 'now-date' :compareDate(date.date, queryParams.nowTime)?'select-date': ''">
        <template #header>
          <div style="display: flex; flex-direction: column; align-items: center">
            <div>{{ date.date.slice(5) }}</div>
            <div>{{ date.title }}</div>
          </div>
        </template>
        <template #default="scope">
          <div :class="checkDateStatus(date.date, scope.row)" @click="openInfo(date.date, scope.row)">
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--  卡片  -->
    <div class="card-container" v-loading="loading" v-if="queryType === 'card'">
      <div v-for="(item, index) in roomList" :key="index" class="card"
           :class="{'card__vacancy':item.orderVO&&!item.orderVO.orderState&& currentOrderType === '2'}"
           @click="openCardInfo(item)"
      >
        <el-card>
          <div class="card-item">
            <div class="card-item__header">
              <div class="card-item__header-left">
                <div class="card-item__header-left-tag"
                     :class="'card-item__header-left-tag--'+orderStateColor(item.orderVO.orderState)"
                     v-if="item.orderVO&&item.orderVO.orderState"
                >
                  <dict-tag :options="dict.type.order_all_state" :value="item.orderVO.orderState"/>
                </div>
                <div class="card-item__header-left-tag card-item__header-left-tag--brown" v-else>
                  空置
                </div>
              </div>
              <div class="card-item__header-right-tag">
                <svg-icon icon-class="zang" v-if="item.sweepState === '1' || item.sweepState === '2'"
                          style="margin-right: 10px; font-size: 18px;color: red;"
                />
              </div>
            </div>
            <div class="card-item__body">
              <div class="card-item__body__title">
                <span>{{ item.premisesAddress }}</span>
              </div>
              <div class="card-item__body__info">
                <span v-if="item.houseOrientation">朝{{ item.houseOrientation }}</span>-<span v-if="item.houseArea"
              >{{ item.houseArea }}m<sup>2</sup></span>
              </div>
              <div class="card-item__body__info">
                <span v-if="item.orderVO&&item.orderVO.orderState">{{ item.orderVO.startTime }}至{{
                    item.orderVO.endTime
                  }}</span>
                <span v-else>空置{{ item.vacancyDay }}天</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div v-if="!roomList.length && !loading" class="no-data">
        <div class="no-data__text">暂无数据</div>
      </div>
    </div>
    <!--  分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      v-if="queryType === 'list'"
    />
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :pageSizes="[12, 24, 36, 48, 60]"
      v-if="queryType === 'card'"
    />
    <!-- 房态信息 -->
    <Info v-model="drawer" :orderId="orderId" :orderType="orderType" :houseId="houseId" @success="getList"/>
  </div>
</template>

<script>
import { estateList } from '@/api/house/estate'
import {
  conditionList,
  conditionCard
} from '@/api/house/condition'
import { getDayOrWeek, inTime } from '@/utils/common/time'
import Info from './components/info'
import { getNextDate } from '@/utils/common/time.js'
import { debounce } from '@/utils'
import { compareDate, compareDateTime, getDate, isBetween } from '@/utils/common/moment'

export default {
  name: 'conditionIndex',
  dicts: ['order_all_state'],
  computed: {
    dateList: {
      get() {
        let startDate =
          new Date(this.queryParams.nowTime).valueOf() - 60 * 60 * 24 * 1000
        let endDate =
          new Date(this.queryParams.nowTime).valueOf() +
          60 * 60 * 24 * 1000 * 30
        return this.getDates(startDate, endDate)
      },
      set(v) {
      }
    },
    //检查日期状态
    checkDateStatus() {
      return (date, row) => {
        //判断房间是否有订单
        let orderVOList = row.orderVOList ? row.orderVOList : []
        if (!orderVOList.length) {
          return 'calendar-default'
        }
        //返回当前日期匹配的订单
        let matchOrder = orderVOList.find(item => isBetween(date, item.startTime, item.endTime, '[]'))
        if (matchOrder) {

          return `calendar-${this.orderStateColor(matchOrder.orderState)}`
        } else {
          return 'calendar-default'
        }
      }
    },
    // 订单状态对应颜色名称
    orderStateColor() {
      return (value) => {
        if (!value) return 'default'
        let orderState = Number(value)
        //长租：待入住:1 短租：待入住:103
        if ([1, 103].includes(orderState)) return 'green'
        //短租:退订中：104
        if ([104].includes(orderState)) return 'red'
        //长租：已入住:7 短租：已入住:106、续租-已支付:152
        if ([7, 106, 152].includes(orderState)) return 'orange'
        //长租：退房中:9、超时退租中:14 短租：退房中:107
        if ([9, 14, 107].includes(orderState)) return 'yellow'
        //长租：协商退租:10、到期退租:11 短租：已完成:108、续租-已完成:154
        if ([10, 11, 108, 154].includes(orderState)) return 'blue'
        //短租：续租-待支付:151
        if ([151].includes(orderState)) return 'gray'
        //长租：退租审核:8、换房审核:12、转租审核:13、续租审核:15
        if ([8, 12, 13, 15].includes(orderState)) return 'purple'
        return 'default'
      }
    },
    queryButton() {
      if (this.currentOrderType === '1') {
        return this.queryButtonList.filter(item => item.value !== '104')
      }
      return this.queryButtonList
    }
  },
  components: {
    Info
  },
  data() {
    return {
      currentOrderType: '1', //当前订单类型：1长短租，2日租
      queryType: 'card',
      drawer: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // 表格数据
      roomList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        estateId: '',
        roomNumber: undefined,
        status: undefined,
        startTime: '',
        endTime: '',
        nowTime: '',
        'housingAllocation.apartmentState': '',
        'housingAllocation.allocationState': '',
        orderState: '', //订单状态：103待入住,104退订中,106已入住,107退房中
        houseState: '', //房间状态：2 空置
        sweepState: '', //脏房字段,
        orderType: '' //订单类型：1长短租，2日租

      },
      // 表单参数
      form: {},

      orderId: '',
      orderType: '',   //订单类型：1长短租，2日租
      houseId: '',//房源id
      orderInfo: {},
      estateList: [],
      list: [],
      total: 0,
      lessee: {},
      current: 0,
      //筛选按钮
      queryButtonList: [
        { label: '全部', value: '' },
        { label: '空置', value: '2' },
        { label: '待入住', value: '103' },
        { label: '退订中', value: '104' },
        { label: '已入住', value: '106' },
        { label: '退房中', value: '107' },
        { label: '审核', value: '8' },
        { label: '脏房', value: '1' }

      ],
      //订单状态提示
      orderStateTipList: [
        { label: '空置', value: '0', class: 'brown' },
        { label: '待入住', value: '1', class: 'green' },
        { label: '退订中', value: '2', class: 'red' },
        { label: '已入住', value: '3', class: 'orange' },
        { label: '退房中', value: '4', class: 'yellow' },
        { label: '已完成', value: '5', class: 'blue' },
        { label: '待付款', value: '6', class: 'gray' },
        { label: '审核', value: '7', class: 'purple' }
      ]
    }
  },
  created() {
    this.screenHeight = window.innerHeight

    //获取当前日期函数
    function getNowFormatDate() {
      let date = new Date(),
        year = date.getFullYear(), //获取完整的年份(4位)
        month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
        strDate = date.getDate() // 获取当前日(1-31)
      if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
      if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0

      return `${year}-${month}-${strDate}`
    }

    this.queryParams.nowTime = getNowFormatDate()
    this.getList()
    this.getEstateList()
  },
  methods: {
    compareDate,
    getDate,
    getNextDate: getNextDate,
    handleQueryType() {
      this.loading = true
      this.total = 0
      this.roomList = []
      if (this.queryType === 'list') {
        this.queryParams.pageSize = 10
      } else if (this.queryType === 'card') {
        this.queryParams.pageSize = 12
      }
      this.resetQuery()
    },
    /** 查询列表 */
    getEstateList() {
      this.loading = true
      estateList().then(
        (response) => {
          this.estateList = response.data
        }
      )
    },
    //房态信息-列表
    openInfo(date, row) {
      let orderVOList = row.orderVOList ? row.orderVOList : []
      if (!orderVOList.length) {
        return
      }
      //返回当前日期匹配的订单
      // let matchOrder = orderVOList.find(item => inTime(date, item.startTime, item.endTime))
      let matchOrder = orderVOList.find(item => isBetween(date, item.startTime, item.endTime, '[]'))
      if (!matchOrder) {
        return
      }
      if (matchOrder.orderType === '1') {
        this.orderId = matchOrder.orderId
      } else if (matchOrder.orderType === '2') {
        this.orderId = matchOrder.linkedOrderId ? matchOrder.linkedOrderId : matchOrder.orderId
      }

      this.orderType = matchOrder.orderType
      this.drawer = true
    },
    /// 房态信息-卡片
    openCardInfo(item) {
      console.log('item', item)
      if (!item.orderVO.orderState && !item.orderVO.orderId && this.currentOrderType === '1') {
        this.drawer = true
        this.orderId = ''
        this.orderType = '1'
        this.houseId = item.houseId
      } else {
        if (!item.orderVO.orderState && !item.orderVO.orderId) return
        this.orderId = item.orderVO.orderId
        this.orderType = item.orderVO.orderType
        this.houseId = item.houseId
        this.drawer = true
      }

    },
    startTimeChange() {
      this.getList()
      this.$forceUpdate()
    },
    //生成日期列表
    getDates(date1, date2, format) {
      let dates = []
      let [startDate, endDate] =
        new Date(date1) < new Date(date2)
          ? [new Date(date1), new Date(date2)]
          : [new Date(date2), new Date(date1)]
      while (startDate <= endDate) {
        dates.push(new Date(startDate))
        startDate.setDate(startDate.getDate() + 1)
      }
      dates = dates.map((item) => {
        item = item
          .toLocaleDateString()
          .split('/')
          .map((items) => {
            items = items.padStart(2, '0')
            return items
          })
          .join(format || '-')
        return {
          date: item,
          status: undefined,
          desc: '描述',
          title: getDayOrWeek(item)
        }
      })
      return dates
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      let interfaceFunc = conditionList
      this.queryParams.startTime = this.dateList[0].date
      this.queryParams.endTime = this.dateList[this.dateList.length - 1].date
      this.queryParams.orderType = this.currentOrderType
      let params = Object.assign({}, this.queryParams)
      //判断是列表还是卡片
      if (this.queryType === 'list') {
        interfaceFunc = conditionList
      } else if (this.queryType === 'card') {
        interfaceFunc = conditionCard
        delete params.startTime
        delete params.endTime
        delete params.nowTime
      }
      interfaceFunc(params).then((response) => {
        this.roomList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.total = 0
        this.roomList = []
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (!this.queryParams.nowTime) {
        this.$message.error('请选择日期')
        return
      }

      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.current = 0
      this.queryParams.orderState = ''
      this.queryParams.houseState = ''
      this.queryParams.sweepState = ''
      this.resetForm('queryForm')
      this.queryParams['housingAllocation.apartmentState'] = ''
      this.queryParams.nowTime = this.$moment().format('YYYY-MM-DD')
      this.handleQuery()
    },
    //请空选择项
    clearSelect() {
      this.$refs.table.clearSelection()
    },
    // 类型切换
    handleOrderTypeClick(item) {
      console.log('item', item)
      this.currentOrderType = item.name
      this.queryParams.orderType = item.name
      this.handleQuery()
    },
    handleQueryButton(item, index) {
      this.current = index
      if (['103', '104', '106', '107'].includes(item.value)) {
        this.queryParams.orderState = item.value
        this.queryParams.houseState = ''
        this.queryParams.sweepState = ''
      } else if (item.value === '2') {
        this.queryParams.orderState = ''
        this.queryParams.houseState = 2
        this.queryParams.sweepState = ''
      } else if (item.value === '1') {
        this.queryParams.orderState = ''
        this.queryParams.houseState = ''
        this.queryParams.sweepState = 1
      } else if (item.value === '8') {
        this.queryParams.orderState = '8'
        this.queryParams.houseState = ''
        this.queryParams.sweepState = ''
      } else {
        this.queryParams.orderState = ''
        this.queryParams.houseState = ''
        this.queryParams.sweepState = ''
      }

      this.handleQuery()

    }

  }
}
</script>
<style lang="scss" scoped>
.title {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}

.total {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-top: 6px;
}

.left-border {
  border-left: 1px solid #999;
}

.right-border {
  border-right: 1px solid #999;
}
::v-deep .now-date{
  background: red !important;
  color: #fff !important;
}
::v-deep .select-date{
  background: red !important;
  color: #fff !important;
}

.info {
  padding: 10px 15px;
  margin: 15px 0;
  background: #e6f7ff;
  color: #1890ff;

  span {
    color: #565c5f;
  }

  .clear {
    margin-left: 20px;
    cursor: pointer;
  }
}

.calendar-status {
  width: 79px;
  height: 30px;
  background-color: green;
  cursor: pointer;
}

.calendar-green {
  width: 79px;
  height: 30px;
  background-color: #70B603;
  cursor: pointer;
}

.calendar-red {
  width: 79px;
  height: 30px;
  background-color: #f67e8d;
  cursor: pointer;
}

.calendar-orange {
  width: 79px;
  height: 30px;
  background-color: #fa9c3c;
  cursor: pointer;
}

.calendar-yellow {
  width: 79px;
  height: 30px;
  background-color: #EFC834;
  cursor: pointer;
}

.calendar-blue {
  width: 79px;
  height: 30px;
  background-color: #007ab0;
  cursor: pointer;
}

.calendar-gray {
  width: 79px;
  height: 30px;
  background-color: #d7d7d7;
  cursor: pointer;
}

.calendar-purple {
  width: 79px;
  height: 30px;
  background-color: #8080FF;
  cursor: pointer;
}

.calendar-default {
  width: 79px;
  height: 30px;
}

.query-button {
  margin-bottom: 30px;
}

::v-deep .el-table__cell {
  padding: 0;
}

::v-deep .cell {
  padding-right: 0;
  padding-left: 0;
}

.order-state-tip {
  display: grid;
  grid-template-columns: repeat(auto-fill, 100px);
  margin-bottom: 20px;

  .state-tip-item {
    display: flex;
    align-items: center;

    .square {
      height: 15px;
      width: 15px;
      border: 1px solid;
      margin-right: 5px;

      .calendar-status {
        background-color: green;
      }

      &.green {
        background-color: #70B603;
      }

      &.red {
        background-color: #f67e8d;
      }

      &.orange {
        background-color: #fa9c3c;
      }

      &.yellow {
        background-color: #EFC834;
      }

      &.blue {
        background-color: #007ab0;
      }

      &.gray {
        background-color: #d7d7d7;
      }

      &.purple {
        background-color: #8080FF
      }

      &.brown {
        background-color: #B8741A;
      }
    }

    span {
      font-size: 12px;
    }
  }

}

.card-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 20px;

  .card {
    cursor: pointer;

    &.card__vacancy {
      cursor: default;
    }

    .card-item {
      .card-item__header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;

        .card-item__header-left-tag {
          width: 80px;
          text-align: center;
          padding: 8px 5px;
          font-size: 12px;
          //background-color: red;
          border-radius: 5px;
          font-weight: 500;
          color: #fff;

          &.card-item__header-left-tag--green { // 待入住
            background-color: #70B603;
          }

          &.card-item__header-left-tag--red { // 退订中
            background-color: #f67e8d;
          }

          &.card-item__header-left-tag--orange { // 已入住
            background-color: #fa9c3c;
          }

          &.card-item__header-left-tag--yellow { // 退房中
            background-color: #EFC834;
          }

          &.card-item__header-left-tag--blue { // 已完成
            background-color: #007ab0;
          }

          &.card-item__header-left-tag--gray { // 待付款
            background-color: #d7d7d7;
          }

          &.card-item__header-left-tag--purple { // 审核中
            background-color: #8080FF;
          }

          &.card-item__header-left-tag--brown { // 空置
            background-color: #B8741A;
          }
        }
      }

      .card-item__body {
        font-size: 14px;

        .card-item__body__title { //一行显示，超出省略号
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .card-item__body__info {
          margin-top: 10px;
        }
      }
    }
  }

  .no-data {
    text-align: center;
    grid-column: 1 / -1;
    margin-top: 50px;
    font-size: 16px;
    color: #999;
  }


}
</style>
